<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户
 * @author www.dingwei.cn
 */
class User extends MY_Controller {
	
	/**
	 * 设置模型
	 * @var AdmSettingModel
	 */
	public $mSetting;
	
	/**
	 * 地址模型
	 * @var ConsumerAddressModel
	 */
	public $mAddress;
	
	/**
	 * 促销模型
	 * @var ConsumerPromotionModel
	 */
	public $mPromotion;
	
	/**
	 * 银行模型
	 * @var ConsumerBankModel
	 */
	public $mBank;
	
	/**
	 * 积分商城模型
	 * @var ConsumerMallModel
	 */
	public $mMall;

    /**
     * 发现模型
     * @var ConsumerFindModel
     */
    public $mFind;

	public function __construct(){
		parent::__construct();
	}

    /**
     * 注册发送短信验证码
     */
    public function getRegisterVerifyCode(){

        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
        );

        $this->formDataValidation($vConf);
        $code = mt_rand(10000,99999);
        $mobile = post('mobile');
        $tB = $this->mUser->mobileIsExist($mobile);
        if($tB){
            $this->appReturn(0, '手机号码已注册');
        }

        $tA = $this->mUser->getSmsCodeLogInfo($mobile);
        if($tA){
            $time = time() - $tA['addtime'];
            if($time < 60){
                $this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
            }
        }

        $query = $this->mUser->addSmsCodeLog($mobile, $code);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }
		$msg = '您正在进行新用户注册登录操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
        $query = sendSms($mobile, $msg);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }

        $this->appReturn(1, '验证码已发送');
    }

	/**
	 * 忘记密码发送短信验证码
	 */
	public function getForgetPasswordVerifyCode(){
	
		//表单验证
		$vConf = array(
				array('mobile', '手机号码', 'required|valid_mobile'),
		);
	
		$this->formDataValidation($vConf);
		$code = mt_rand(10000,99999);
		$mobile = post('mobile');
		$tB = $this->mUser->mobileIsExist($mobile);
		if( ! $tB){
			$this->appReturn(0, '手机号码未注册');
		}
	
		$tA = $this->mUser->getSmsCodeLogInfo($mobile);
		if($tA){
			$time = time() - $tA['addtime'];
			if($time < 60){
				$this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
			}
		}
	
		$query = $this->mUser->addSmsCodeLog($mobile, $code);
		if( ! $query){
			$this->appReturn(0, '验证码发送失败');
		}
		$msg = '您正在进行登录密码找回操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
		$query = sendSms($mobile, $msg);
		if( ! $query){
			$this->appReturn(0, '验证码发送失败');
		}
	
		$this->appReturn(1, '验证码已发送');
	}

    /**
     *验证发送手机发送的验证码是否合法
     */
    public function verifyMobileCode(){
        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required'),
        );
        $this->formDataValidation($vConf);
        $mobile = trim($this->input->post('mobile'));
        $code = trim($this->input->post('code'));

        //验证验证码
        $tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);
        if(empty($tA)) $this->appReturn(0, '验证码错误');
        /*$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
        if($tA['addtime'] < $smsExpire){
            $this->appReturn(0, '验证码过期');
        }*/

        //验证手机
        $userId = $this->mUser->mobileIsExist($mobile);
        if( ! $userId){
            $this->appReturn(0, '手机号码未注册');
        }
        $this->appReturn(1, '验证成功');
    }

    /**
     * 检查验证码是否正确
     */
    public function checkVerifyCode(){
    	//表单验证
    	$vConf = array(
    			array('mobile', '手机号码', 'required|valid_mobile'),
    			array('code', '验证码', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$mobile = trim(post('mobile'));
    	$code = trim(post('code'));
    	
    	//获取验证码
    	$tCode = $this->mUser->getSmsCodeLogInfo($mobile,$code);
    	if ( ! $tCode){
    		$this->appReturn(0, '验证码错误');
    	}
    	
    	$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
    	if($tCode['addtime'] < $smsExpire){
    		$this->appReturn(0, '验证码过期');
    	}
		//只验证，不删除，等注册时，一起提交，删除验证码    	
    	$this->appReturn(1,'验证成功');
    }

    /**
     * 发送短信验证码
     */
    public function getVerifyCode(){

        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
        );

        $this->formDataValidation($vConf);
        $code = mt_rand(10000,99999);
        $mobile = post('mobile');

        $tA = $this->mUser->getSmsCodeLogInfo($mobile);
        if($tA){
            $time = time() - $tA['addtime'];
            if($time < 60){
                $this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
            }
        }

        $query = $this->mUser->addSmsCodeLog($mobile, $code);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }
        $msg = $code.'（登录验证码，如非本人请忽略！）戈壁市集，为您提供即买即送的手机买菜服务！';
        $query = sendSms($mobile, $msg);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }

        $this->appReturn(1, '验证码已发送');
    }

    /**
     * 验证码登录
     */
    public function loginByCode(){
        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required'),
        );
        $this->formDataValidation($vConf);
        $mobile = post('mobile');
        $code = post("code");

        //验证验证码
        $sc = $this->mUser->getSmsCodeLogInfo($mobile, $code);
        if(empty($sc)) $this->appReturn(0, '验证码错误');
        $smsExpire = time() - getCustomConfig('sms_expire') * 3600;
        if($sc['addtime'] < $smsExpire){
            $this->appReturn(0, '验证码过期');
        }

        //验证手机
        $userId = $this->mUser->mobileIsExist($mobile);
        if($userId){
            //登录
            //设置sessid
            $tA = $this->mUser->getInfo($userId);
            $key = config_item('encryption_key');
            $sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
            if(empty($sessionId)){
                $this->appReturn(0, '登录失败');
            }

            if($this->mUser->addSession($tA['id'], $sessionId)){
                $this->sessionId = $sessionId;
                $data = array(
                    'user_id' => $tA['id'],
                    'sessionid' => encode($sessionId),
                    'jpush_code' => $tA['jpush_code'],
                    'easemob_code' => '',
                    'easemob_pwd'=>'',
                    'name' => $tA['nickname'],
                    'is_pay_passwd'=>empty($tA['pay_passwd'])?"1":"2",
                );

                if ( ! $this->mUser->save(array('last_login_time'=>time()),$tA['id'])){
                    $this->appReturn(0, '登录失败', $data);
                }

                $this->appReturn(1, '已登录', $data);
            }

            $this->appReturn(0, '登录失败');
        }else{
            //注册
            $jpush_code = uniqid().rand(1000, 9999).rand(100, 9999);
            $password = substr($mobile, -6); // 初试密码为手机号后六位
            //注册账户信息
            $data = array(
                'mobile' => $mobile,
                'nickname' => substr($mobile,0,3).'****'.substr($mobile, -4),
                'password' => setPassword($password),
                'jpush_code' => $jpush_code,
                'message_push' => 2,
                'status' => 2,
                'balance' => 0,
                'addtime' => time(),
                'easemob_code'=> uniqid().rand(1000, 9999).rand(100, 9999)//环信账号
            );
            $data['easemob_pwd'] = setPassword($data['easemob_code']);//环信密码

            $this->db->trans_begin();
            if( $uId = $this->mUser->save($data)){

                //删除验证码
                if( !($this->mUser->deleteSmsCode($mobile))){
                    $this->db->trans_rollback();
                    $this->appReturn(0, '注册失败');
                }

                //设置sessid
                $key = config_item('encryption_key');
                $sessionId = encryption($uId.$key.time().mt_rand(10,100000));
                if(empty($sessionId)){
                    $this->db->trans_rollback();
                    $this->appReturn(0, '注册失败');
                }
                //注册送红包
                $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');
                $this->db->select('id,name,type,money,surplus_number,send_start_time,send_end_time')
                    ->where(array('type' => 3,'status' => 2,'surplus_number >' => 0,'send_start_time <='=> time(),'send_end_time >=' => time()));
                $bonusList = $this->mPromotion->getAll($this->mPromotion->tbBonus);

                if($bonusList){
                    $bA = array();
                    $else = array();
                    foreach ($bonusList as $v){
                        $bA[] = array(
                            'bonus_id' => $v['id'],
                            'type' => $v['type'],
                            'consumer_id' => $uId,
                            'money' => $v['money'],
                            'status' => 1,
                            'addtime' => time()
                        );
                        $else[] = array(
                            'id' => $v['id'],
                            'surplus_number' => $v['surplus_number'] - 1,
                        );
                    }
                    if(!($this->mPromotion->saveBonusLog($bA, 0, true))){
                        $this->db->trans_rollback();
                        $this->appReturn(0, '红包赠送失败');
                    }
                    //更新剩余红包数量
                    if(!($this->mPromotion->save($else, 0, true))){
                        $this->db->trans_rollback();
                        $this->appReturn(0, '红包赠送失败');
                    }
                }

                // 注册赠送积分数量
                $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
                $this->loadModel('ConsumerMallModel', 'mMall');
                $number = $this->mSetting->get('regiser_integral_number'); // 注册赠送积分数量
                if ($number > 0){
                    $integral = $this->mUser->save(array('integral'=> $number), $uId);
                    if (!$integral){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                    // 添加积分记录
                    $integralLogData = array(
                        'consumer_id' => $uId,
                        'type' => 2,
                        'integral' => $number,
                        'status' => 2,
                        'addtime' => time(),
                    );
                    $integralLog = $this->mMall->saveLog($integralLogData);
                    if (!$integralLog){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                }

                // 注册经验奖励数量
                $this->loadModel('ConsumerExperienceValueModel', 'mExperience');
                $experience = $this->mSetting->get('register_experience_value_number'); // 注册经验奖励数量
                if ($experience > 0){
                    $exp = $this->mUser->save(array('experience_value'=> $experience), $uId);
                    if (!$exp){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                    // 添加经验奖励记录
                    $logData = array(
                        'consumer_id' => $uId,
                        'type' => 1,
                        'experience_value' => $number,
                        'addtime' => time(),
                    );
                    $log = $this->mExperience->save($logData);
                    if (!$log){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                }

                //赠送包邮卡
                $this->loadModel('ConsumerPostalCardModel', 'mPostalCard', 'consumer');
                $info = $this->mPostalCard->getCard(['type'=>1,'status'=>2]);
                if(!empty($info)){
                    for($i = 0 ; $i < $info['send_number'] ; $i++ ){
                        $lData[] = array(
                            'postal_card_id' => $info['id'],
                            'type' => $info['type'],
                            'consumer_id' => $uId,
                            'order_id' => 0,
                            'money' => $info['money'],
                            'status' => 1,
                            'addtime' => time(),
                            'begintime'=> time(),
                            'userendtime'=>strtotime("+".$info['use_date'].' days')
                        );
                    }
                    if(isset($lData)){
                        $tA = $this->mPostalCard->insertBatch($this->mPostalCard->tbPostalCardLog, $lData);
                        if (!$tA){
                            $this->db->trans_rollback();
                            $this->ajaxReturn(0, '注册失败');
                        }
                        //推送消息
                        $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
                        $title = '赠送'.$info['send_number'].'张包邮体验券，享免费配送到家.';
                        $content = '亲，'.$info['send_number'].'张包邮体验券已存入您的账户，让您尊享生鲜果蔬1小时免费配送到家，请您查收。';
                        $msgdata[] = array(
                            'consumer_id' => $uId,
                            'type' => 2,
                            'title' => $title,
                            'content' => $content,
                            'content_detail' => $content,
                            'addtime' => time(),
                        );
                        $tA = $this->mMessage->batchSave($msgdata);
                        if (!$tA){
                            $this->db->trans_rollback();
                            $this->ajaxReturn(0, '推送失败');
                        }
                        jpush($title, $content, 1, $data['jpush_code']);
                    }
                }

                if($this->mUser->addSession($uId, $sessionId)){
                    $this->sessionId = $sessionId;
                    $data = array(
                        'sessionid' => encode($sessionId)
                    );
                    $this->db->trans_commit();
                    $this->appReturn(1, '注册成功', $data);
                }
            }
        }
    }

    /**
     * 用户注册
     */
    public function register(){

        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required'),
            array('password', '密码', 'required|min_length[6]|max_length[15]'),
            array('re_password', '确认密码', 'required|matches[password]'),
        );
        $this->formDataValidation($vConf);
        $mobile = trim(post('mobile'));
        $code = trim(post('code'));

        //验证手机
        $userId = $this->mUser->mobileIsExist($mobile);
        if($userId){
        	$this->appReturn(0, '手机号码已注册');
        }
        
        //验证验证码
        $tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);
        if(empty($tA)) $this->appReturn(0, '验证码错误');
        $smsExpire = time() - getCustomConfig('sms_expire') * 3600;
        if($tA['addtime'] < $smsExpire){
            $this->appReturn(0, '验证码过期');
        }

        $jpush_code = uniqid().rand(1000, 9999).rand(100, 9999);

        //注册账户信息
        $data = array(
            'mobile' => $mobile,
            'nickname' => substr($mobile,0,3).'****'.substr($mobile, -4),
            'password' => setPassword(post('password')),
        	'jpush_code' => $jpush_code,
            'message_push' => 2,
            'status' => 2,
            'balance' => 0,
            'addtime' => time(),
            'easemob_code'=> uniqid().rand(1000, 9999).rand(100, 9999)//环信账号
        );
        $data['easemob_pwd'] = setPassword($data['easemob_code']);//环信密码

        $this->db->trans_begin();
        if( $uId = $this->mUser->save($data)){

            //删除验证码
            if( !($this->mUser->deleteSmsCode($mobile))){
                $this->db->trans_rollback();
                $this->appReturn(0, '注册失败');
            }

            //设置sessid
            $key = config_item('encryption_key');
            $sessionId = encryption($uId.$key.time().mt_rand(10,100000));
            if(empty($sessionId)){
                $this->db->trans_rollback();
                $this->appReturn(0, '注册失败');
            }
            //注册送红包
            $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');
            $this->db->select('id,name,type,money,surplus_number,send_start_time,send_end_time')
                ->where(array('type' => 3,'status' => 2,'surplus_number >' => 0,'send_start_time <='=> time(),'send_end_time >=' => time()));
            $bonusList = $this->mPromotion->getAll($this->mPromotion->tbBonus);

            if($bonusList){
                $bA = array();
                $else = array();
                foreach ($bonusList as $v){
                    $bA[] = array(
                        'bonus_id' => $v['id'],
                        'type' => $v['type'],
                        'consumer_id' => $uId,
                        'money' => $v['money'],
                        'status' => 1,
                        'addtime' => time()
                    );
                    $else[] = array(
                        'id' => $v['id'],
                        'surplus_number' => $v['surplus_number'] - 1,
                    );
                }
                if(!($this->mPromotion->saveBonusLog($bA, 0, true))){
                    $this->db->trans_rollback();
                    $this->appReturn(0, '红包赠送失败');
                }
                //更新剩余红包数量
                if(!($this->mPromotion->save($else, 0, true))){
                    $this->db->trans_rollback();
                    $this->appReturn(0, '红包赠送失败');
                }
            }

            // 注册赠送积分数量
            $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
            $this->loadModel('ConsumerMallModel', 'mMall');
            $number = $this->mSetting->get('regiser_integral_number'); // 注册赠送积分数量
            if ($number > 0){
                $integral = $this->mUser->save(array('integral'=> $number), $uId);
                if (!$integral){
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '注册失败');
                }
                // 添加积分记录
                $integralLogData = array(
                    'consumer_id' => $uId,
                    'type' => 2,
                    'integral' => $number,
                    'status' => 2,
                    'addtime' => time(),
                );
                $integralLog = $this->mMall->saveLog($integralLogData);
                if (!$integralLog){
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '注册失败');
                }
            }

            // 注册经验奖励数量
            $this->loadModel('ConsumerExperienceValueModel', 'mExperience');
            $experience = $this->mSetting->get('register_experience_value_number'); // 注册经验奖励数量
            if ($experience > 0){
                $exp = $this->mUser->save(array('experience_value'=> $experience), $uId);
                if (!$exp){
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '注册失败');
                }
                // 添加经验奖励记录
                $logData = array(
                    'consumer_id' => $uId,
                    'type' => 1,
                    'experience_value' => $number,
                    'addtime' => time(),
                );
                $log = $this->mExperience->save($logData);
                if (!$log){
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '注册失败');
                }
            }

            //赠送包邮卡
            $this->loadModel('ConsumerPostalCardModel', 'mPostalCard', 'consumer');
            $info = $this->mPostalCard->getCard(['type'=>1,'status'=>2]);
            if(!empty($info)){
                for($i = 0 ; $i < $info['send_number'] ; $i++ ){
                    $lData[] = array(
                        'postal_card_id' => $info['id'],
                        'type' => $info['type'],
                        'consumer_id' => $uId,
                        'order_id' => 0,
                        'money' => $info['money'],
                        'status' => 1,
                        'addtime' => time(),
                        'begintime'=> time(),
                        'userendtime'=>strtotime("+".$info['use_date'].' days')
                    );
                }
                if(isset($lData)){
                    $tA = $this->mPostalCard->insertBatch($this->mPostalCard->tbPostalCardLog, $lData);
                    if (!$tA){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                    //推送消息
                    $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
                    $title = '赠送'.$info['send_number'].'张包邮体验券，享免费配送到家.';
                    $content = '亲，'.$info['send_number'].'张包邮体验券已存入您的账户，让您尊享生鲜果蔬1小时免费配送到家，请您查收。';
                    $msgdata[] = array(
                        'consumer_id' => $uId,
                        'type' => 2,
                        'title' => $title,
                        'content' => $content,
                        'content_detail' => $content,
                        'addtime' => time(),
                    );
                    $tA = $this->mMessage->batchSave($msgdata);
                    if (!$tA){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '推送失败');
                    }
                    jpush($title, $content, 1, $data['jpush_code']);
                }
            }

            if($this->mUser->addSession($uId, $sessionId)){
                $this->sessionId = $sessionId;
                $data = array(
                    'sessionid' => encode($sessionId)
                );
                $this->db->trans_commit();
                $this->appReturn(1, '注册成功', $data);
            }
        }
    }

	/**
	 * 用户登录
	 */
	public function login(){
		//表单验证
		$vConf = array(
					array('mobile', '手机号码', 'required|valid_mobile'),
					array('password', '密码', 'required|min_length[6]|max_length[15]'),
				);

		$this->formDataValidation($vConf);
		$mobile = trim(post('mobile'));
		$password = setPassword(post('password'));

		$tA = $this->mUser->getInfoByMobileAndPassword($mobile, $password);
		if(empty($tA)){
			$this->appReturn(0, '用户不存在或密码错误');
		}
		if($tA['status'] < 2){
			$this->appReturn(0, '账户已禁用');	
		}
		
		//设置sessid
		$key = config_item('encryption_key');
		$sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
		if(empty($sessionId)){
			$this->appReturn(0, '登录失败');				
		}
		
		if($this->mUser->addSession($tA['id'], $sessionId)){
			$this->sessionId = $sessionId;
			$data = array(
                		'user_id' => $tA['id'],
                		'sessionid' => encode($sessionId),
						'jpush_code' => $tA['jpush_code'],
						'easemob_code' => $tA['easemob_code'],
						'easemob_pwd'=>$tA['easemob_pwd'],
                        'name' => $tA['nickname'],
						'is_pay_passwd'=>empty($tA['pay_passwd'])?"1":"2",
			);	
			
			if ( ! $this->mUser->save(array('last_login_time'=>time()),$tA['id'])){
				$this->appReturn(0, '登录失败', $data);
			}
			
			$this->appReturn(1, '已登录', $data);		
		}
		

		
		$this->appReturn(0, '登录失败');
	}
	
	/**
	 * 忘记密码
	 */
	public function forgetPassword(){
		//表单验证
		$vConf = array(
					array('mobile', '手机号码', 'required|valid_mobile'),
					array('code', '验证码', 'required'),
					array('password', '密码', 'required|min_length[6]|max_length[15]'),
					array('re_password', '确认密码', 'required|matches[password]'),
				);
		$this->formDataValidation($vConf);	
		$mobile = trim(post('mobile'));
		$code = trim(post('code'));

		//验证验证码
		$tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);	
		if(empty($tA)) $this->appReturn(0, '验证码错误');
		$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
		if($tA['addtime'] < $smsExpire){
			$this->appReturn(0, '验证码过期');				
		}
		
		//验证手机
		$userId = $this->mUser->mobileIsExist($mobile);
		if( ! $userId){
			$this->appReturn(0, '手机号码未注册');
		}
		
		$data = array(
			       'password' => setPassword(post('password'))
				);
				
		if($this->mUser->save($data, $userId)){
			$this->mUser->deleteSmsCode($mobile);//删除验证码
			$this->appReturn(1, '密码已更改');
		}
		
		$this->appReturn(0, '修改失败');
	}

    /**
     * 修改密码
     */
    public function password(){

        //表单验证
        $vConf = array(
            array('old_password', '旧密码', 'required|min_length[6]|max_length[15]'),
            array('password', '新密码', 'required|min_length[6]|max_length[15]'),
            array('re_password', '确认密码', 'required|matches[password]'),
        );
        $this->formDataValidation($vConf);
        $mobile = $this->userMobile;

        $oldPassword = setPassword(post('old_password'));
        //验证手机
        $userId = $this->mUser->getInfoByMobileAndPassword($mobile, $oldPassword);
        if(empty($userId)){
            $this->appReturn(0, '原密码错误');
        }

        $data = array(
            'password' => setPassword(post('password'))
        );

        if($this->mUser->save($data, $this->userId)){
            $this->appReturn(1, '密码修改成功，请重新登录');
        }
        $this->appReturn(0, '修改失败');
    }
    
    /**
     * 获取用户个人信息
     */
    public function getInfo(){
        $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');
    	$info = $this->mUser->getInfo($this->userId);
    	$info['portrait'] = $info['portrait']['xs'];
        $info['bonus'] = $this->mPromotion->getConsumerBonusNumber($this->userId); // 可用红包个数
        $info['coupon'] = $this->mPromotion->getConsumerCouponNumber($this->userId); // 可用代金券个数
    	$this->appReturn(1,'',$info);
    }
    
    /**
     * 获取各新消息状态
     */
    public function getMsgStatus(){
    	
    	$this->loadModel('ConsumerMessageModel', 'mMsg','consumer');
    	$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
    	$this->loadModel('ConsumerCartModel', 'mCart','consumer');
    	$this->loadModel('ConsumerOrderModel', 'mOrder','consumer');
    	$tA = array(
    			'balance'=>1,//新消息
    			'integral'=>1,//新消息
    			'bonus'=>$this->mPromotion->appGetBonusLogList($this->userId, 1,0,true) > 0 ? "2":"1",
    			'coupon'=>$this->mPromotion->appGetCouponLogList($this->userId, 1,0,true) > 0 ? "2":"1",
    			'message_num' =>$this->mMsg->getMessageTotal($this->userId,1),
    			'order_num' => $this->mMsg->getMessageTotal($this->userId,2),
    			'shop_car_num'=>$this->mCart->getProductCount($this->userId),//购物车数量
    			'order_operation'=>$this->mOrder->getOperateOrderNumber(0,$this->userId),//可操作订单数量
    	);
    	
    	$this->appReturn(1,'',$tA);
    }
    
    /**
     * 上传头像
     */
    public function portrait(){
        error_reporting(E_ALL^E_WARNING^E_NOTICE);//显示除去E_WARNING E_NOTICE 之外的所有错误信息
    	$path = 'uploads/member/'.$this->port.'/'.$this->userId.'/portrait';
    	if(empty($_FILES['portrait'])){
    		$this->ajaxReturn(0, '请选择上传头像');
    	}
    	
    	$tA = imageUpload($path, 'portrait', 'portrait', true, 250, 250);
    	if( ! $tA['status']){
    		$this->appReturn(0, '头像上传失败');
    	}
    	$rs = $this->mUser->save(array('portrait' => $tA['data']), $this->userId);
    	if($rs){
    		$this->appReturn(1, '头像上传成功', getImage($tA['data'], 'xs'));
    	}
    	$this->appReturn(0, '头像上传失败');
    }
    
    /**
     * 设置支付密码
     */
    public function setPayPasswd(){
    	//表单验证
    	$vConf = array(
    			array('code', '短信验证码', 'required'),
    			array('password', '支付密码', 'required|min_length[6]'),
    			array('repassword', '确认密码', 'required|matches[password]|min_length[6]'),
    	);
    	$this->formDataValidation($vConf);
    	//获取
    	$code = post('code');
    	$password = post('password');
    	$repassword = post('repassword');
    	
    	/**
    	 * 验证手机
    	 */
    	if ( ! $this->mUser->mobileIsExist($this->userMobile)){
    		$this->appReturn(0,'手机号错误');
    	}
    	
    	/**
    	 * 验证验证码
    	 */
    	$tCode = $this->mUser->getSmsCodeLogInfo($this->userMobile, $code);
    	if(! $tCode){
    		$this->appReturn(0, '验证码错误');
    	}
    	$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
    	if($tCode['addtime'] < $smsExpire){
    		$this->appReturn(0, '验证码过期');
    	}
    	
    	/**
    	 * 设置密码
    	 */
    	$this->db->trans_begin();//事务
    	
    	if ( ! $this->mUser->save(array('pay_passwd'=>setPassword($password)),$this->userId)){
    		$this->db->trans_rollback();
    		$this->appReturn(0,'设置密码失败');
    	}
    	
    	//删除验证码
    	if ( ! $this->mUser->deleteSmsCode($this->userMobile)){
    		$this->db->trans_rollback();
    		$this->appReturn(0,'设置失败');
    	}
    	
		$this->db->trans_commit();    	
    	$this->appReturn(1,'设置成功');
    }
    
    /**
     * 修改支付密码
     */
    public function savePayPasswd(){
    	//表单验证
    	$vConf = array(
    			array('oldpassword', '旧支付密码', 'required|min_length[6]'),
    			array('password', '支付密码', 'required|min_length[6]'),
    			array('repassword', '确认密码', 'required|matches[password]|min_length[6]'),
    	);
    	$this->formDataValidation($vConf);
    	//获取
    	$oldpassword = post('oldpassword');
    	$password = post('password');
    	$repassword = post('repassword');
    	
    	/**
    	 * 验证密码
    	 */
    	if ( ! $tInfo = $this->mUser->getInfo($this->userId)){
    		$this->appReturn(0,'登录失效');
    	}
    	
    	if ($tInfo['pay_passwd'] !== setPassword($oldpassword)){
    		$this->appReturn(0,'旧支付密码错误');
    	}
    	
    	/**
    	 * 修改密码
    	 */
    	if ( ! $this->mUser->save(array('pay_passwd'=>setPassword($password)),$this->userId)){
    		$this->appReturn(0,'修改失败');
    	}
    	
    	$this->appReturn(1,'修改成功');
    }
    
    /**
     * 修改登录密码
     */
    public function savePasswd(){
    	//表单验证
    	$vConf = array(
    			array('oldpassword', '旧支密码', 'required|min_length[6]'),
    			array('password', '新密码', 'required|min_length[6]'),
    			array('repassword', '确认密码', 'required|matches[password]|min_length[6]'),
    	);
    	$this->formDataValidation($vConf);
    	//获取
    	$oldpassword = post('oldpassword');
    	$password = post('password');
    	$repassword = post('repassword');
    	
    	/**
    	 * 验证密码
    	 */
    	if ( ! $tInfo = $this->mUser->getInfo($this->userId)){
    		$this->appReturn(0,'登录失效');
    	}
    	
    	if ($tInfo['password'] !== setPassword($oldpassword)){
    		$this->appReturn(0,'旧密码错误');
    	}
    	
    	/**
    	 * 修改密码
    	 */
    	if ( ! $this->mUser->save(array('password'=>setPassword($password)),$this->userId)){
    		$this->appReturn(0,'修改失败');
    	}
    	
    	$this->appReturn(1,'修改成功');
    }
    
    /**
     * 获取支付密码发送短信验证码
     */
    public function getPayPasswdVerifyCode(){
    	
    	$code = mt_rand(10000,99999);
    	$tB = $this->mUser->mobileIsExist($this->userMobile);
    	if( ! $tB){
    		$this->appReturn(0, '手机号码未注册');
    	}
    	
    	$tA = $this->mUser->getSmsCodeLogInfo($this->userMobile);
    	if($tA){
    		$time = time() - $tA['addtime'];
    		if($time < 60){
    			$this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
    		}
    	}
    	
    	$query = $this->mUser->addSmsCodeLog($this->userMobile, $code);
    	if( ! $query){
    		$this->appReturn(0, '验证码发送失败');
    	}
		 $msg = '您正在进行支付密码设置操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
    	//获取用户信息
        $userInfo = $this->mUser->getInfo($this->userId);
    	if($userInfo['has_pay_passwd'] == 2){
    	    $msg = '您正在进行支付密码找回操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
        }
    	$query = sendSms($this->userMobile, $msg);
    	if( ! $query){
    		$this->appReturn(0, '验证码发送失败');
    	}
    	
    	$this->appReturn(1, '验证码已发送');
    }

    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	第三方登录
    //-----------------------------------------------

    /**
     * 第三方登录短信验证码
     */
    public function getThirdVerifyCode(){

        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
        );

        $this->formDataValidation($vConf);
        $code = mt_rand(10000,99999);
        $mobile = post('mobile');
        $tA = $this->mUser->getSmsCodeLogInfo($mobile);
        if($tA){
            $time = time() - $tA['addtime'];
            if($time < 60){
                $this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
            }
        }

        $query = $this->mUser->addSmsCodeLog($mobile, $code);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }

        $tB = $this->mUser->mobileIsExist($mobile);
        //已注册过
        $msg = '该手机号正在进行第三方登录绑定，验证码'.$code.'，如非本人操作请忽略此短信。';
        if( ! $tB){
            //未注册
           $msg = '您正在进行第三方绑定操作，验证码'.$code.'，绑定成功后也可使用该手机号登录，初始密码为手机后6位，请尽快修改。';
        }

        $query = sendSms($mobile, $msg);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }

        $this->appReturn(1, '验证码已发送');
    }

    /**
     * 第三方登录
     */
    public function thirdParty(){
        //表单验证
        $vConf = array(
            array('type', '第三方对应值', 'required|in_list[1,2]'), // 1 微信（wxUnionId）   2 QQ（qqUnionId）
            array('value', 'unionId的值', 'required'),
        );
        $this->formDataValidation($vConf);
        $type = post('type');// wxUnionId,qqUnionId
        $value = post('value');
        $keyword = $type == 1 ? 'wxUnionId' : 'qqUnionId';
        $tA = $this->mUser->getInfoByMobileAndPassword(0, 0, array($keyword => $value));
        if(!empty($tA)){
            if($tA['status'] < 2){
                $this->appReturn(0, '账户已禁用');
            }
            //设置sessid
            $key = config_item('encryption_key');
            $sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
            if(empty($sessionId)){
                $this->appReturn(0, '登录失败');
            }
            if($this->mUser->addSession($tA['id'], $sessionId)){
                $this->sessionId = $sessionId;
                $data = array(
                    'user_id' => $tA['id'],
                    'sessionid' => encode($sessionId),
                    'jpush_code' => $tA['jpush_code'],
                    'easemob_code' => $tA['easemob_code'],
                    'easemob_pwd'=>$tA['easemob_pwd'],
                    'name' => $tA['nickname'],
                    'mobile' => $tA['mobile'],
                    'is_pay_passwd'=>empty($tA['pay_passwd'])?"1":"2",
                );

                if ( ! $this->mUser->save(array('last_login_time'=>time()),$tA['id'])){
                    $this->appReturn(0, '登录失败', $data);
                }

                $this->appReturn(1, '已登录', $data);
            }
        }else{
            $this->appReturn(-1,'请绑定账号');
        }
    }

    /**
     * 第三方绑定
     *
     */
    public function thirdBinding(){
        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required'),
            array('type', '第三方对应值', 'required|in_list[1,2]'),// 1 微信（wxUnionId）   2 QQ（qqUnionId）
            array('value', 'unionId的值', 'required'),
//            array('head_portrait', '头像', 'required'),
        );
        $this->formDataValidation($vConf);
        $mobile = post('mobile');
        $code = post("code");
        $type = post("type");
        $keyword = $type == 1 ? 'wxUnionId' : 'qqUnionId';
        $value = post('value');
//        $head_portrait = post('head_portrait'); // 头像


        //验证验证码
        $sc = $this->mUser->getSmsCodeLogInfo($mobile, $code);
        if(empty($sc)) $this->appReturn(0, '验证码错误');
        $smsExpire = time() - getCustomConfig('sms_expire') * 3600;
        if($sc['addtime'] < $smsExpire){
            $this->appReturn(0, '验证码过期');
        }

        //验证手机
        $userId = $this->mUser->mobileIsExist($mobile);

        if($userId){
            // 手机号码已注册, 绑定第三方信息
            $tA = $this->mUser->getInfoByMobileAndPassword(0, 0, array('id' => $userId));
            if($tA['status'] < 2){
                $this->appReturn(0, '账户已禁用');
            }
            $data = array($keyword => $value);
            $rS = $this->mUser->save($data, $userId);
            if (!$rS){
                $this->appReturn(0, '绑定失败');
            }
        }else{
            // 未注册， 添加新用户绑定第三方登陆
            $password = substr($mobile, -6); // 初试密码为手机号后六位
            $data = array(
                'mobile' => $mobile,
                'nickname' => substr($mobile,0,3).'****'.substr($mobile, -4),
                'status' => 2,
                'jpush_code' => uniqid().rand(1000, 9999).rand(100, 9999),
                'password' => setPassword($password),
                'addtime' => time(),
                $keyword => $value
            );
            $userId = $this->mUser->save($data);
            if (!$userId){
                $this->appReturn(0, '绑定失败');
            }
            //注册送红包
            $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');
            $this->db->select('id,name,type,money,surplus_number,send_start_time,send_end_time')
                ->where(array('type' => 3,'status' => 2,'surplus_number >' => 0,'send_start_time <='=> time(),'send_end_time >=' => time()));
            $bonusList = $this->mPromotion->getAll($this->mPromotion->tbBonus);

            if($bonusList){
                $bA = array();
                $else = array();
                foreach ($bonusList as $v){
                    $bA[] = array(
                        'bonus_id' => $v['id'],
                        'type' => $v['type'],
                        'consumer_id' => $userId,
                        'money' => $v['money'],
                        'status' => 1,
                        'addtime' => time()
                    );
                    $else[] = array(
                        'id' => $v['id'],
                        'surplus_number' => $v['surplus_number'] - 1,
                    );
                }
                if(!($this->mPromotion->saveBonusLog($bA, 0, true))){
                    $this->db->trans_rollback();
                    $this->appReturn(0, '红包赠送失败');
                }
                //更新剩余红包数量
                if(!($this->mPromotion->save($else, 0, true))){
                    $this->db->trans_rollback();
                    $this->appReturn(0, '红包赠送失败');
                }
            }

            //赠送包邮卡
            $this->loadModel('ConsumerPostalCardModel', 'mPostalCard', 'consumer');
            $info = $this->mPostalCard->getCard(['type'=>1,'status'=>2]);
            if(!empty($info)){
                for($i = 0 ; $i < $info['send_number'] ; $i++ ){
                    $lData[] = array(
                        'postal_card_id' => $info['id'],
                        'type' => $info['type'],
                        'consumer_id' => $userId,
                        'order_id' => 0,
                        'money' => $info['money'],
                        'status' => 1,
                        'addtime' => time(),
                        'begintime'=> time(),
                        'userendtime'=>strtotime("+".$info['use_date'].' days')
                    );
                }
                if(isset($lData)){
                    $tA = $this->mPostalCard->insertBatch($this->mPostalCard->tbPostalCardLog, $lData);
                    if (!$tA){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '注册失败');
                    }
                    //推送消息
                    $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
                    $title = '赠送'.$info['send_number'].'张包邮体验券，享免费配送到家.';
                    $content = '亲，'.$info['send_number'].'张包邮体验券已存入您的账户，让您尊享生鲜果蔬1小时免费配送到家，请您查收。';
                    $msgdata[] = array(
                        'consumer_id' => $userId,
                        'type' => 2,
                        'title' => $title,
                        'content' => $content,
                        'content_detail' => $content,
                        'addtime' => time(),
                    );
                    $tA = $this->mMessage->batchSave($msgdata);
                    if (!$tA){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '推送失败');
                    }
                    jpush($title, $content, 1, $data['jpush_code']);
                }

            }

            $tA = $this->mUser->getInfoByMobileAndPassword(0, 0, array('id' => $userId));
        }

        //设置sessid
        $key = config_item('encryption_key');
        $sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
        if(empty($sessionId)){
            $this->appReturn(0, '登录失败');
        }
        if($this->mUser->addSession($tA['id'], $sessionId)){
            $this->sessionId = $sessionId;
            $data = array(
                'sessionid' => encode($sessionId),
                'jpush_code' => $tA['jpush_code'],
                'easemob_code' => $tA['easemob_code'],
                'easemob_pwd'=>$tA['easemob_pwd'],
                'name' => $tA['nickname'],
                'is_pay_passwd'=>empty($tA['pay_passwd'])?"1":"2",
            );

            if ( ! $this->mUser->save(array('last_login_time'=>time()),$tA['id'])){
                $this->appReturn(0, '登录失败', $data);
            }

            $this->appReturn(1, '已登录', $data);
        }
    }

    /**
     *  第三方解绑
     */
    public function offBinding(){
        //表单验证
        $vConf = array(
            array('type', '第三方对应值', 'required|in_list[1,2]'), // 1 微信（wxUnionId）   2 QQ（qqUnionId）
        );
        $this->formDataValidation($vConf);
        $type = post('type');// wxUnionId,qqUnionId
        $keyword = $type == 1 ? 'wxUnionId' : 'qqUnionId';
        $tA = $this->mUser->save(array($keyword => ''), $this->userId);
        if(!$tA){
            $this->appReturn(0,'解绑失败');
        }
        $this->appReturn(1,'解绑成功');
    }

    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	收货地址
    //-----------------------------------------------
    
    public function getAddress(){
    	//表单验证
 /*    	$vConf = array(
    			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf); */
    	
    	//$page = trim(post('page'));

    	$this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
        $lat = trim(post('latitude'));
        $lng = trim(post('longitude'));

    	$tA = $this->mAddress->appGetList($this->userId, 1, false, $lat, $lng);
    	$this->appReturn(1,'',$tA);
    }
    
    /**
     * 获取默认地址
     */
    public function getAddressDefault(){
    	$this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
    	$lat = trim(post('latitude'));
    	$lng = trim(post('longitude'));
    	$tA = $this->mAddress->getDefaultAddress($this->userId, $lat, $lng);
    	$this->appReturn(1,'获取成功',$tA);
    }

    /**
     * 添加收货地址
     */
    public function saveAddress(){
    	//表单验证
    	$vConf = array(
    			array('consignee', '收货人名称', 'required'),
    			array('gender', '性别', 'required|in_list[1,2]'),
    			array('mobile', '电话', 'required|valid_mobile'),
    			array('province', '省份id', 'required|is_natural_no_zero'),
    			array('city', '市id', 'required|is_natural_no_zero'),
    			array('county', '区id', 'required|is_natural_no_zero'),
    			array('address', '详细地址', 'required'),
    			array('latitude', '经度', 'required'),
    			array('longitude', '纬度', 'required'),
    			array('street', '街道门牌号', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$addressId= trim(post('address_id'));//地址id 【有则 编辑】
    	
    	$consignee = trim(post('consignee'));
    	$gender = trim(post('gender'));
    	$mobile = trim(post('mobile'));
    	$province = trim(post('province'));
    	$city = trim(post('city'));
    	$county = trim(post('county'));
    	$address = trim(post('address'));
    	$latitude = trim(post('latitude'));
    	$longitude = trim(post('longitude'));
    	$street = trim(post('street'));

        $addressIds = array();
        if (!in_array($province, $addressIds)){
            $addressIds[] = $province;
        }
        if (!in_array($city, $addressIds)){
            $addressIds[] = $city;
        }
        if (!in_array($county, $addressIds)){
            $addressIds[] = $county;
        }

        $address_str = '';
        if ($addressIds){
            $this->loadModel('AdmSettingModel','mSetting','admin');
            $tAddress = $this->mSetting->getLocationNameByIds($addressIds);
            $address_str = $tAddress[$province]['name'] . $tAddress[$city]['name'] . $tAddress[$county]['name'].$address;
        }

        if ( ! $address_str){
            $this->appReturn(0,'地址不存在');
        }
        //地址验证
//        $tVerAddress = $this->verifyAddress($address_str,$latitude,$longitude);
//    	if ( ! $tVerAddress['status']){
//            $this->appReturn(0,$tVerAddress['message']);
//        }

    	//数据
		$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
		
    	$data = array(
    			'consumer_id'=>$this->userId,
    			'consignee'=>$consignee,
    			'gender'=>$gender,
    			'mobile'=>$mobile,
    			'province'=>$province,
    			'city'=>$city,
    			'county'=>$county,
    			'address'=>$address,
    			'latitude'=>$latitude,
    			'longitude'=>$longitude,
    			'street'=>$street,
    	);
    	
    	if ($addressId){
    		if( ! $this->mAddress->save($data,$addressId)){
    			$this->appReturn(0,'保存失败');
    		}
    	}else{
    		//如果没有地址
    		$data['is_default'] = 1;
    		if ( ! $this->mAddress->getInfo(0,$this->userId)){
    			$data['is_default'] = 2;
    		}
    		
    		$data['addtime'] = time();
    		if( ! $this->mAddress->save($data)){
    			$this->appReturn(0,'保存失败');
    		}
    		

    	}
    	
    	$this->appReturn(1,'保存成功');
    }

    /**
     * 验证地址是否准确
     * @param $address
     * @param $latitude
     * @param $longitude
     * @return array
     */
    private function verifyAddress($address,$latitude, $longitude){
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        $this->loadModel('DlnOrderModel', 'mDln', 'deliveryman');

        $config = $this->mSett->get('map_key', 'deliveryman');

        $url = 'http://api.map.baidu.com/geocoder/v2/?address='.$address.'&output=json&ak='.$config;
        $tA = $this->mDln->_request($url);

        if($tA == false){
            return ['status' => 0, 'message' => '地址解析错误'];
        }

        $tS = getDistance($latitude, $longitude, $tA[0], $tA[1]);

        if( ! is_numeric($tS) || $tS > 100){
            return ['status' => 0, 'message' => '当前地址与经纬度有误差'.$tS];
        }
        return ['status'=>1,'message'=>''];
    }

    /**
     * 移除收货地址
     * 地址如果使用过，或者有关联，则假删
     */
    public function rmAddress(){
    	//表单验证
    	$vConf = array(
    			array('address_id', '地址id', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$addressId = trim(post('address_id'));
    	
    	$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
    	
    	if ( ! $this->mAddress->getInfo($addressId, $this->userId)){
    		$this->appReturn(0,'已经删除了');
    	}
    	
    	//删除
    	if ( ! $this->mAddress->deleteAddress($addressId, $this->userId)){
    		$this->appReturn(0,'删除失败');
    	}
    	
    	$this->appReturn(1,'删除成功');
    }
    
    /**
     * 设置默认地址
     */
    public function setAddressDefault(){
    	//表单验证
    	$vConf = array(
    			array('address_id', '地址id', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$addressId = trim(post('address_id'));
    	
    	$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
    	if ( ! $this->mAddress->getInfo($addressId, $this->userId)){
    		$this->appReturn(0,'没有该地址');
    	}
    	
    	if ( ! $this->mAddress->save(array('is_default'=>1),0,$this->userId)){
    		$this->appReturn(0,'设置失败');
    	}
    	
    	if ( ! $this->mAddress->save(array('is_default'=>2),$addressId)){
    		$this->appReturn(0,'设置失败');
    	}
    	
    	$this->appReturn(1,'设置成功');
    }
    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	余额
    //-----------------------------------------------
    /**
     * 获取余额记录
     */
    public function getBalanceLog(){
    	//表单验证
    	$vConf = array(
//     			array('time', '时间', 'required'),
    			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$page = trim(post('page'));
    	$time = trim(post('time'));
    	$type = trim(post('type'));
    	
    	$tA['balance'] = $this->userBalance;
    	$tA['list'] = $this->mUser->appGetBuyLogList($this->userId,$type,$time,$page);
    	$this->appReturn(1,'',$tA);
    }
    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	银行卡
    //-----------------------------------------------
    /**
     * 获取银行卡列表
     */
    public function getBankList(){
    	//表单验证
    	$vConf = array(
    			array('type_id', '银行卡类型', 'required|is_natural_no_zero'),
//     			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$typeId = trim(post('type_id'));
    	$page = trim(post('page'));
    	
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	$tA = $this->mBank->appGetBankList($this->userId,$typeId);
    	foreach ($tA as $k=>$v){
    		$tA[$k]['account_number'] = $this->mBank->HidesNumber($v['account_number'],4,4);
    	}
    	
    	$this->appReturn(1,'',$tA);
    }
    
    /**
     * 增加银行卡
     */
    public function addBankCard(){
    	//表单验证
    	$vConf = array(
    			array('bank_id', '银行卡id', 'required|is_natural_no_zero'),
    			array('account_name', '卡名称', 'required'),
    			array('account_number', '卡号', 'required'),
    			array('mobile', '联系电话', 'required|valid_mobile'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$bankId = trim(post('bank_id'));
    	$account_name = trim(post('account_name'));
    	$account_number = trim(post('account_number'));
    	$mobile = trim(post('mobile'));
    	
    	//获取银行卡
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	$tBank = $this->mBank->getAdminBank($bankId);
    	if ( ! $tBank){
    		$this->appReturn(0,'银行卡类型不存在');
    	}
    	
    	$data = array(
    			'consumer_id'=>$this->userId,
    			'type'=>1,
    			'icon'=>$tBank['bank_icon'],
    			'account_name'=>$account_name,
    			'account_number'=>$account_number,
    			'open_bank'=>$tBank['bank_name'],
    			'mobile'=>$mobile,
    			'addtime'=>time(),
    	);
    	
    	$tId = $this->mBank->save($data);
    	if ( ! $tId){
    		$this->appReturn(0,'添加失败');
    	}
    	
    	$this->appReturn(1,'添加成功');
    }
    
    /**
     * 增加支付宝
     */
    public function addAlipay(){
    	//表单验证
    	$vConf = array(
    			array('account_name', '卡名称', 'required'),
    			array('account_number', '卡号', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$account_name = trim(post('account_name'));
    	$account_number = trim(post('account_number'));
    	
    	//获取银行卡
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	
    	$data = array(
    			'consumer_id'=>$this->userId,
    			'type'=>2,
    			'icon'=>'',
    			'account_name'=>$account_name,
    			'account_number'=>$account_number,
    			'open_bank'=>'支付宝',
    			'mobile'=>$account_number,
    			'addtime'=>time(),
    	);
    	
    	$tId = $this->mBank->save($data);
    	if ( ! $tId){
    		$this->appReturn(0,'添加失败');
    	}
    	
    	$this->appReturn(1,'添加成功');
    }
    
    /**
     * 移除银行卡
     */
    public function rmBankCard(){
    	//表单验证
    	$vConf = array(
    			array('card_id', 'id', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$cardId = post('card_id');
    	
    	//获取银行卡
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	
    	if ( ! $this->mBank->getInfo($cardId,$this->userId)){
    		$this->appReturn(0,'银行卡不存在');
    	}
    	
    	//删除银行卡
    	$this->db->where('id',$cardId);
    	$this->db->where('consumer_id',$this->userId);
    	if ( ! $this->db->delete($this->mBank->tbBank)){
    		$this->appReturn(0,'移除失败');
    	}
    	
    	$this->appReturn(1,'移除成功');
    }
    
    /**
     * 移除支付宝
     */
 /*    public function rmAlipay(){
    	//表单验证
    	$vConf = array(
    			array('card_id', 'id', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$cardId = post('card_id');
    	
    	//获取银行卡
    	$this->loadModel('ConsumerBankModel', 'mBank', 'consumer');
    	
    	if ( ! $this->mBank->getInfo($cardId,$this->userId)){
    		$this->appReturn(0,'银行卡不存在');
    	}
    	
    	//删除银行卡
    	$this->db->where('id',$cardId);
    	$this->db->where('consumer_id',$this->userId);
    	if ( ! $this->db->delete($this->mBank->tbBank)){
    		$this->appReturn(0,'移除失败');
    	}
    	
    	$this->appReturn(1,'移除成功');
    } */
    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	积分记录
    //-----------------------------------------------
    /**
     * 获取积分记录
     */
    public function getIntegralLog(){
    	//表单验证
    	$vConf = array(
    			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$page = trim(post('page'));
    	$time = trim(post('time'));
    	$type = trim(post('type'));
    	
    	/**
    	 * 时间查询
    	 * @var string $starttime
    	 */
    	
    	$this->loadModel('ConsumerMallModel', 'mMall','consumer');
    	
    	$tA['integral'] = $this->userIntegral;
    	$tA['list'] = $this->mMall->appGetIntegralLogList($this->userId,$type,$time,$page);
    	
    	$this->appReturn(1,'',$tA);
    	
    }
    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	红包
    //-----------------------------------------------
    /**
     * 获取红包列表
     */
    public function getBonusList(){
    	//表单验证
    	$vConf = array(
    			array('status', '红包状态', 'required|is_natural_no_zero|in_list[1,2,3]'),
    			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$status = trim(post('status'));//1未使用 2-使用 3-过期
    	$page = trim(post('page'));
    	$condition = post('condition');//条件
    	
    	$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
    	$tA = $this->mPromotion->appGetBonusLogList($this->userId,$status,$page,false,$condition);
    	
    	$data = array(
    			'list'=>$tA,
    			'not_use'=>(string)$this->mPromotion->appGetBonusLogList($this->userId, 1,0,true),
    			'use'=>(string)$this->mPromotion->appGetBonusLogList($this->userId, 2,0,true),
    			'out_date'=>(string)$this->mPromotion->appGetBonusLogList($this->userId, 3,0,true),
    	);
    	
    	$this->appReturn(1,'',$data);
    }

    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	包邮卡
    //-----------------------------------------------
    /**
     * 获取包邮卡列表
     */
    public function getPostalCardList(){
    	//表单验证
    	$vConf = array(
    			array('status', '包邮卡状态', 'required|is_natural_no_zero|in_list[1,2,3]'),
    			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);

    	$status = trim(post('status'));//1未使用 2-使用 3-过期
    	$page = trim(post('page'));

        $this->loadModel('ConsumerPostalCardModel', 'mPostalCard','consumer');
        $list = $this->mPostalCard->appGetBonusLogList($this->userId,$status,$page);

        $data = array(
            'list' => $list,
            'not_use'=>(string)$this->mPostalCard->appGetBonusLogList($this->userId, 1,0,true),
            'use'=>(string)$this->mPostalCard->appGetBonusLogList($this->userId, 2,0,true),
            'out_date'=>(string)$this->mPostalCard->appGetBonusLogList($this->userId, 3,0,true),
        );

    	$this->appReturn(1,'',$data);
    }
    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	代金劵
    //-----------------------------------------------
    /**
     * 获取代金劵列表
     */
    public function getCouponList(){
    	//表单验证
    	$vConf = array(
    			array('status', '红包状态', 'required|is_natural_no_zero'),
    			array('page', '分页', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$status = trim(post('status'));//1未使用 2-使用 3-过期
    	$page = trim(post('page'));
    	$condition = post('condition');//条件
    	$merchantId = post('merchant_id');//条件
    	
    	if ($condition && ! $merchantId){
	    	//商家id没有传，也为空
	    	$this->appReturn(0,'商家id不能为空');
	    }
    	
    	
    	$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
    	$tA = $this->mPromotion->appGetCouponLogList($this->userId,$status,$page,false,$condition,$merchantId);
    	
    	if ($tA){
    		$tMerchant = array();
    		$merchantIds = array();
	    	foreach ($tA as $k=>$v){
	    		if (!in_array($v['merchant_id'], $merchantIds)){
	    			$merchantIds[] = $v['merchant_id'];
	    		}
	    	}
	    	//获取商家信息
	    	if ($merchantIds){
		    	$this->loadModel('MerchantUserModel', 'mMerchant','merchant');
		    	$tMerchant = $this->mMerchant->getInfoByIds($merchantIds);
	    	}
	    	
	    	foreach ($tA as $k=>$v){
	    		$tA[$k]['s_name'] = isset($tMerchant[$v['merchant_id']]) ? $tMerchant[$v['merchant_id']]['shop_name'] : '';
	    		$tA[$k]['s_icon'] = isset($tMerchant[$v['merchant_id']]) ? $tMerchant[$v['merchant_id']]['portrait'] : '';
	    	}
    	}
    	$data = array(
    			'list'=>$tA,
    			'not_use'=>(string)$this->mPromotion->appGetCouponLogList($this->userId, 1,0,true),
    			'use'=>(string)$this->mPromotion->appGetCouponLogList($this->userId, 2,0,true),
    			'out_date'=>(string)$this->mPromotion->appGetCouponLogList($this->userId, 3,0,true),
    	);
    	
    	$this->appReturn(1,'',$data);
    }
    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	收藏信息
    //-----------------------------------------------
    /**
     * 获取收藏列表
     */
    public function getCollectionList(){
    	//表单验证
    	$vConf = array(
            array('type', '类型', 'required|is_natural_no_zero|in_list[1,2]'),//1-店铺 2-便民服务
            array('page', '分页', 'is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	$type = post('type');
    	$page = post('page');
    	$latitude = post('latitude');
    	$longitude = post('longitude');
    	
    	$tA = $this->mUser->appGetCollectionList($this->userId, $type,$page,$latitude,$longitude);
    	
    	$this->appReturn(1,'',$tA);
    }
    
    /**
     * 添加收藏
     */
    public function saveCollection(){
    	//表单验证
    	$vConf = array(
    			array('relation_id', '收藏内容id', 'required|is_natural_no_zero'),
    			array('type', '收藏类型', 'required|is_natural_no_zero|in_list[1,2,3]'),//1-店铺 2-便民服务 3 - 便民服务关注
    	);
    	$this->formDataValidation($vConf);
    	
    	$type = trim(post('type'));
    	$relationId = trim(post('relation_id'));
    	
    	//获取关联的文章信息
    	switch ($type){
    		case 1:
    			//获取店铺
    			get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
    			if ( ! $tData = $this->mMerchant->getInfo($relationId)){
    				$this->appReturn(0,'店铺不存在');
    			}
    			break;
    		case 2:
    			//获取便民服务
    			get_instance()->loadModel('ConsumerFindModel', 'mFind', 'consumer');
    			if ( ! $tData = $this->mFind->getInfo($relationId, true)){
    				$this->appReturn(0,'发现不存在');
    			}
    			break;
            case 3:
                //获取便民服务关注
                get_instance()->loadModel('ConsumerFindCategoryModel', 'mFindCategory', 'consumer');
                if ( ! $tData = $this->mFindCategory->getInfo($relationId,true)){
                    $this->appReturn(0,'分类不存在');
                }
                break;
    		default:
    			$tData = array();
    	}
    	
    	//是否收藏
    	if ($this->mUser->hasCollection($this->userId, $relationId, $type)){
    		$this->appReturn(0,'您已经收藏过');
    	}
    	
    	//收藏
    	$data = array(
            'consumer_id'=>$this->userId,
            'relation_id'=>$relationId,
            'type'=>$type,
            'addtime'=>time(),
    	);
    	
    	if ( ! $this->mUser->saveCollection($data)){
    		$this->appReturn(0,'收藏失败');
    	}
    	
    	$this->appReturn(1,'收藏成功');
    }
    
    /**
     * 移除收藏
     */
    public function rmCollection(){
    	//表单验证
    	$vConf = array(
    			array('relation_id', '收藏内容id', 'required|is_natural_no_zero'),
    			array('type', '收藏类型', 'required|is_natural_no_zero|in_list[1,2,3]'),//1-店铺 2-便民服务 3 - 便民服务关注
    			
    	);
    	$this->formDataValidation($vConf);
    	
    	$relationId = trim(post('relation_id'));
    	$type = trim(post('type'));
    	
    	if ( ! $this->mUser->hasCollection($this->userId, $relationId, $type)){
    		$this->appReturn(0,'已经取消了');
    	}
    	
    	if ( ! $this->mUser->removeCollection($this->userId, $relationId, $type)){
    		$this->appReturn(0,'取消失败');
    	}
    	
    	$this->appReturn(1,'取消成功');
    }
    
    
	////////////////////////////////////////////////////////////
	//-----------------------------------------------
	//|	反馈信息
	//-----------------------------------------------
	
    /**
     * 获取反馈列表
     */
    public function getFeedbackList(){
    	//表单验证
    	$vConf = array(
    			array('page', '分页', 'required|is_natural_no_zero'),
    			
    	);
    	$this->formDataValidation($vConf);
    	
    	$page = trim(post('page'));
    	
    	$this->loadModel('AdmFeedbackModel', 'mFeedback', 'admin');
    	$tA = $this->mFeedback->appGetFeedbackList($this->userId, 0, $page);
    	
    	$this->appReturn(1,'',$tA['list']);
    }
    
    /**
     * 提交反馈信息
     */
    public function saveFeedback(){
    	//表单验证
    	$vConf = array(
    			array('content', '反馈内容', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$content = trim(post('content'));
    	
    	$this->loadModel('AdmFeedbackModel', 'mFeedback', 'admin');
    	
    	$data = array(
    			'consumer_id'=>$this->userId,
    			'merchant_id'=>0,
    			'content'=>$content,
    			'reply'=>'',
    			'status'=>1,
    			'addtime'=>time(),
    	);
    	
    	if ( ! $this->mFeedback->save($data)){
    		$this->appReturn(0,'反馈失败');
    	}
    	
    	$this->appReturn(1,'反馈成功');
    }

    
    ////////////////////////////////////////////////////////////
    //-----------------------------------------------
    //|	个人信息
    //-----------------------------------------------
    /**
     * 编辑个人信息
     */
    public function save(){
    	//表单验证
  /*   	$vConf = array(
    			array('nickname', '昵称', 'required'),
    			array('realname', '真实名称', 'required'),
    	);
    	$this->formDataValidation($vConf); */
    	
    	$nickname = trim(post('nickname'));
    	$realname = trim(post('realname'));
    	
    	$data = array();
    	if ($nickname){
    		$data['nickname'] = $nickname;
    	}
    	if ($realname){
    		$data['realname'] = $realname;
    	}
    	
    	if ( ! $data){
    		$this->appReturn(0,'数据错误');
    	}
    	
    	if ( ! $this->mUser->save($data,$this->userId)){
    		$this->appReturn(0,'保存失败');
    	}
    	
    	$this->appReturn(1,'保存成功');
    }
    
    /**
     * 调试
     */
    public function test(){
    	$sm = QCsendSms('15736107187',1,array('222222'));
    	p($sm);
    }

    /**
     * 获取app版本
     * type = 1 安卓
     * type = 2 ios
     */
    public function getAppVersionInfo(){
        $this->loadModel('AdmSettingModel', 'mSet', 'admin');
        //表单验证
        $vConf = array(
            array('type', 'app类型', 'required|in_list[1,2]'),
        );

        $type = get('type');
        $this->formDataValidation($vConf,array('type' => $type));

        if($type == 1){
            $tA = $this->mSet->get('app_android_update');
            $data = json_decode($tA, true);
        }else{
            $tA = $this->mSet->get('app_ios_update');
            $data = json_decode($tA, true);
        }


        $this->appReturn(1, '', $data[0]);
    }

    /**
     * 进入首页更新登录时间
     */
    public function updateLastLoginTime(){
        if ( ! $this->mUser->save(array('last_login_time'=>time()),$this->userId)){
            $this->appReturn(0, '更新失败');
        }
        $this->db->trans_begin();
        $this->_addIntegral(3);
        $this->_addExperienceValue(2);
        $this->db->trans_commit();
        $this->appReturn(1, '更新成功');
    }

    /**
     * 推广
     */
    public function extend(){
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');

        $share = $this->mSetting->get('sharp_title,sharp_icon,sharp_url,sharp_desc');
        $share['sharp_icon'] = getImage($share['sharp_icon'],'og');
        $share['sharp_url'] = getUrl('user/shares?pid='.$this->userId);
        $share['code'] = 'http://qr.liantu.com/api.php?el=l&m=10&w=200&text='.$share['sharp_url'];

        //专题信息
        $this->db->select('share_img,register_img,down_img,share_step,content');

        $tA = $this->mSetting->getOne($this->mSetting->tbShare);

        $tA['share_img'] = base_url($tA['share_img']);
        $tA['register_img'] = base_url($tA['register_img']);
        $tA['down_img'] = base_url($tA['down_img']);
        $tA['share_step'] = base_url($tA['share_step']);
        //统计
        $this->db->where('parent_id', $this->userId);
        $tA['consumerCount'] = $this->mUser->count($this->mUser->tbUser);//用户数量

        $this->db->select('sum(amount) as amount')
            ->where(array('consumer_id' => $this->userId, 'type' => 7, 'status' => 2));
        $amount = $this->mUser->getOne($this->mUser->tbBuyLog);//佣金
        $tA['amount'] = $amount['amount']?$amount['amount']:0;

        $this->db->where(array('consumer_id' => $this->userId, 'type' => 1));
        $tA['bonusCount'] = $this->mPromotion->count($this->mPromotion->tbBonusLog);//红包数量
        //分享记录
        $this->db->select('p.id, p.nickname, count(b.id) as bonusCount, count(u.id) as consumerCount')
            ->join($this->mUser->tbUser. ' p', 'p.id = u.parent_id')
            ->join($this->mPromotion->tbBonusLog. ' b', 'b.consumer_id = p.id and b.type = 1', 'left')
            ->where(array('p.status >' => 0, 'u.parent_id >' => 0))
            ->group_by('p.id')
            ->order_by('consumerCount', 'RANDOM');
        $tA['list'] = $this->mUser->getAll($this->mUser->tbUser .' u');

        $html = $this->view('share/extend',['title' => '分享得红包','pid' => $this->userId,'share'=>$share,'info' => $tA]
            ,0,0,0,true);

        $this->appReturn(1, '', $html);

    }

}